package com.isaac.service;

import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.rpc.*;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.*;

@Activate(group = {CommonConstants.CONSUMER})
public class TPMonitorFilter extends Thread implements Filter {

    Map<String, List<Integer>> recordMap = new HashMap<>();

    @Override
    public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
        // 1.记录调用耗时
        long epochMilli = Instant.now().toEpochMilli();
        Result invoke = invoker.invoke(invocation);

        final LocalDateTime now = LocalDateTime.now();
        Instant endInstant = now.atZone(ZoneId.systemDefault()).toInstant();

        // 方法耗时
        int costMills = (int) (endInstant.toEpochMilli() - epochMilli);
        // 方法名
        String methodName = invocation.getMethodName();

        if (now.getSecond() % 5 == 0) {
            System.out.println("当前打印日志时间:" + now.getHour()+ ":" + now.getMinute()+ ":" + now.getSecond());
            new printCostTimeThread(recordMap).start();
        }


        if (!recordMap.containsKey(methodName)) {
            recordMap.put(methodName, new ArrayList<>());
        }

        recordMap.get(methodName).add(costMills);

        return invoke;
    }


}

